package com.eshipenet.shipnet.edgeboxextbuilder

import play.api.libs.json.JsObject

import scala.util.Try

sealed trait EdgeBoxAction {
  val id: String
  val raw: DebeziumParser.Action
  val actionInfo: DebeziumActionInfo = DebeziumActionInfo(raw)
}

case class EdgeBoxInsert(id: String, after: EdgeBox, raw: DebeziumParser.Insert)                  extends EdgeBoxAction
case class EdgeBoxUpdate(id: String, before: EdgeBox, after: EdgeBox, raw: DebeziumParser.Update) extends EdgeBoxAction
case class EdgeBoxDelete(id: String, before: EdgeBox, raw: DebeziumParser.Delete)                 extends EdgeBoxAction

object EdgeBoxAction {

  private def wrapEdgeBox(box: JsObject): EdgeBox = {
    val id      = (box \ "id").as[String]
    val modelId = (box \ "modelId").as[String]
    EdgeBox(id = id, modelId = modelId, data = box)
  }

  def apply(act: DebeziumParser.Action): Try[EdgeBoxAction] = act match {
    case insert @ DebeziumParser.Insert(after, _) =>
      Try {
        val box = wrapEdgeBox(after)
        EdgeBoxInsert(box.id, box, insert)
      }
    case update @ DebeziumParser.Update(before, after, _) =>
      Try {
        val boxBefore = wrapEdgeBox(before)
        val boxAfter  = wrapEdgeBox(after)
        EdgeBoxUpdate(boxAfter.id, boxBefore, boxAfter, update)
      }
    case delete @ DebeziumParser.Delete(before, _) =>
      Try {
        val box = wrapEdgeBox(before)
        EdgeBoxDelete(box.id, box, delete)
      }
  }

}
